package com.learn.rpc.version.version4;

import com.learn.rpc.common.AdminUser;
import com.learn.rpc.common.AdminUserServiceImpl;
import com.learn.rpc.common.FinalParam;
import com.learn.rpc.common.IAdminUserService;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author wangxing
 * @version 2020/8/15 7:03 Administrator
 */
public class RpcServer {
    static boolean running = true;

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(FinalParam.PORT);
        while (running){
            try {
                Socket accept = serverSocket.accept();
                process(accept);
                accept.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    private static void process(Socket socket) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
//        获取数据输入流
        ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
//        获取数据输出流
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
//        获取传递过来的id参数
        String methodName = objectInputStream.readUTF();
        Class[] paramsTypes = (Class[]) objectInputStream.readObject();
        Object[] args = (Object[]) objectInputStream.readObject();
//        根据参数进行数据调用
        IAdminUserService adminUserService = new AdminUserServiceImpl();
        Method method = adminUserService.getClass().getMethod(methodName, paramsTypes);
        Object object = method.invoke(adminUserService, args);
//        进行数据远程输出
        objectOutputStream.writeObject(object);

        objectOutputStream.close();
        objectInputStream.close();
    }

}
